package userManage

import (
	"github.com/gin-gonic/gin"
	"log"
	"main/src/utils"
)

func Login(c *gin.Context) {
	body := &LoginDto{}
	if err := utils.ShouldBind(c, body); err != nil {
		return
	}
	token, validateErr, errStatus := body.ValidateUser()
	if validateErr != nil {
		utils.Response(
			c,
			validateErr.Error(),
			errStatus,
			nil,
		)
		return
	}

	utils.Response(
		c,
		"ok",
		utils.Status.Ok,
		token,
	)
}

func GetUser(c *gin.Context) {
	body := &GetUserDto{}

	if err := utils.ShouldBind(c, &body); err != nil {
		return
	}
	users, err := body.Get(c)
	if err != nil {
		return
	}
	log.Println(users)
	utils.Response(
		c,
		"ok",
		utils.Status.Ok,
		users,
	)
}

func CreateUser(c *gin.Context) {
	body := &CreateUserDto{}
	if err := utils.ShouldBind(c, &body); err != nil {
		return
	}
	user, err := body.Create(c)
	if err != nil {
		return
	}

	utils.Response(
		c,
		"ok",
		utils.Status.Ok,
		user,
	)
}

func DeleteUser(c *gin.Context) {
	body := &DeleteUserDto{}
	if err := utils.ShouldBind(c, &body); err != nil {
		return
	}
	if err := body.DeleteUser(c); err != nil {
		return
	}

	utils.Response(
		c,
		"ok",
		utils.Status.Ok,
		nil,
	)
}

func UpdateBackUp(c *gin.Context) {
	body := &BackUpUserDto{}
	if err := utils.ShouldBind(c, &body); err != nil {
		return
	}
	user, err := body.BackUpUser(c)
	if err != nil {
		return
	}
	res := &UserInfoResponseDto{}
	res.format(*user)
	utils.Response(
		c,
		"ok",
		utils.Status.Ok,
		res,
	)
}

func SetSuperUser(c *gin.Context) {
	body := &SetSuperDto{}
	if err := utils.ShouldBind(c, &body); err != nil {
		return
	}
	user, err := body.SetSuper(c)
	if err != nil {
		return
	}
	res := &UserInfoResponseDto{}
	res.format(*user)
	utils.Response(
		c,
		"ok",
		utils.Status.Ok,
		res,
	)
}

func EditPassword(c *gin.Context) {
	body := &EditPasswordDto{}
	if err := utils.ShouldBind(c, &body); err != nil {
		return
	}
	err := body.EditPassword(c)
	if err != nil {
		return
	}
	utils.Response(
		c,
		"ok",
		utils.Status.Ok,
		nil,
	)
}
